package com.runvp.handler;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.core.redis.RedisLockClient;
import com.runvp.common.enums.*;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.utils.DateUtils;
import com.runvp.service.biz.domain.BizOrder;
import com.runvp.service.biz.handler.CmdCommonHandler;
import com.runvp.service.tcp.TcpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class CmdDeviceResStartChargHandler {

    @Autowired
    private CmdCommonHandler cmdCommonHandler;
    @Autowired
    private RedisLockClient lockClient;
    @Autowired
    private TcpService tcpService;
    /**
     * 设备回应服务器发下发启动充电指令
     * @param parseBody
     * @return MessageResBody
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageResBody handle(MessageReceiveBody parseBody){
        log.info("设备回应服务器下发启动充电指令处理:::receiveBody:{}",JSONObject.toJSONString(parseBody));
        String batchNo = System.nanoTime()+"";
        StringBuilder tips = new StringBuilder();
        tcpService.addBizTcpRecord(parseBody.setBatchNo(batchNo));
        JSONObject body = parseBody.getBodyJson();
        String oid = body.getString("oid");
        BizOrder order = tcpService.instanceIBizOrderService().selectBizOrderByOrderNo(oid);
        if(null == order){
            boolean startStatus = startStatus(body,tips, ToolUtils.toInt(oid));
            log.info("调试订单【{}】充电开启结果【{}】",oid,startStatus);
            if(startStatus){
                tcpService.instanceIBizDeviceCargoService().usePort(ToolUtils.objTOLong(oid), CargoUseStatus.USE.getCode());
                log.info("调试订单【{}】端口锁定成功",oid);
            }
        }else {
            boolean startStatus = startStatus(body,tips, order.getPort());
            log.info("常规订单【{}】充电开启结果【{}】",oid,startStatus);
            if(startStatus){
                //执行扣款
                String type = order.getType();
                String opMsg = "充电消费";
                if (PayChannel.PAY_SCORE.getCode().equals(type)) {
                    opMsg = "扫码充电: ";
                } else if (PayChannel.PAY_CLOUD_CARD.getCode().equals(type)) {
                    opMsg = "刷卡充电: ";
                }
                cmdCommonHandler.buildCustomerTranLog(opMsg,order);
                order.setPayStatus(OrderPayStatus.PAY_SUCCESS.getCode());
                order.setPayAmount(order.getAmount());
                order.setPayTime(DateUtils.getNowDate());
                order.setRemark(order.getRemark()+tips);
                order.setStatus(OrderStatus.GO_ON.getCode());
                //启用订单
                order.setEnable(EnableStatus.ENABLE.getCode());
                tcpService.instanceIBizOrderService().updateBizOrder(order);
                //修改端口状态为使用中
                tcpService.instanceIBizDeviceCargoService().usePort(order.getCargoId(), CargoUseStatus.USE.getCode());
                log.info(opMsg+"常规订单【{}】端口锁定成功",oid);
            }
        }
        log.info("设备回应服务器下发启动充电指令处理:::无需回应resBody: null");
        return null;
    }

    /**
     * 判断充电开启状态
     * @param body
     * @param tips
     * @param port
     * @return boolean
     */
    private boolean startStatus(JSONObject body,StringBuilder tips,Integer port){
        Integer rs = body.getInteger("rs");
        Integer er = body.getInteger("er");
        String msg = String.format("\n时间【%s】",DateUtils.getTime());
        //启动结果 1:成功 0：失败
        if(!rs.equals(1)){
            String errorMsg = msg+"启动充电失败:";
            ///错误码，0：无错误 1：故障 2：端口占用
            if(er.equals(1)){
                //1：故障
                errorMsg += "【端口"+port+" 故障】";
            }
            if(er.equals(2)){
                //2：端口占用
                errorMsg += "【端口"+port+" 占用】";
            }
            tips.append(errorMsg);
            log.info("设备回应服务器下发启动充电指令业务处理:{}",errorMsg);
            return false;
        }else {
            String succMsg = msg+"充电启动成功";
            tips.append(succMsg);
            log.info("设备回应服务器下发启动充电指令业务处理:{}",succMsg);
            return true;
        }
    }
}
